package com.my.job.service;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.my.job.common.Page;
import com.my.job.domain.CronTriggers;
import com.my.job.domain.CronTriggersExample;
import com.my.job.domain.Triggers;
import com.my.job.domain.TriggersExample;
import com.my.job.mapper.CronTriggersMapper;
import com.my.job.mapper.TriggersMapper;
import com.my.job.util.PageUtils;

@Service
public class SchedulerService
{
	@Autowired
	private TriggersMapper triggersMapper;
	
	@Autowired
	private CronTriggersMapper cronTriggersMapper;
	
	public Page<Triggers> list(Triggers trigger,Page<Triggers> page) 
	{
		TriggersExample example = new TriggersExample();
		TriggersExample.Criteria criteria = example.createCriteria();
		
		if(StringUtils.isNotEmpty(trigger.getTriggerName()))
		{
			criteria.andTriggerNameEqualTo(trigger.getTriggerName());
		}
		if(StringUtils.isNotEmpty(trigger.getTriggerGroup()))
		{
			criteria.andTriggerGroupEqualTo(trigger.getTriggerGroup());
		}
		
		if (page == null)
		{
			page = new Page<Triggers>(10);
		}
		else
		{
			page = PageUtils.setPageToExample(page, example);
		}

		int total = triggersMapper.countByExample(example);
		List<Triggers> list = triggersMapper.selectByExample(example);
		page.setTotalCount(total);
		page.setResult(list);

		return page;
	}
	
	public String getCron(CronTriggers cronTriggers)
	{
		if(cronTriggers==null || cronTriggers.getTriggerName()==null || cronTriggers.getTriggerGroup()==null)
		{
			return null;
		}
		
		CronTriggersExample example = new CronTriggersExample();
		CronTriggersExample.Criteria criteria = example.createCriteria();
		
		criteria.andTriggerGroupEqualTo(cronTriggers.getTriggerGroup());
		criteria.andTriggerNameEqualTo(cronTriggers.getTriggerName());
		
		List<CronTriggers> list = cronTriggersMapper.selectByExample(example);
		
		if(CollectionUtils.isEmpty(list) || list.size()>1)
		{
			return null;
		}
		
		CronTriggers cron = list.get(0);
		
		return cron.getCronExpression();
	}
	
	
}
